import React, { useRef, useState } from "react";
import { Button, Modal, Form } from "react-bootstrap";

/**
 * 验证器函数。
 * @callback  ValidatorFunction
 * @param {string} value 输入值
 * @returns {string} 验证结果。若验证通过，返回 null；否则返回错误信息。
 */

/**
 * InputBox 组件。
 * @param {object} props 
 * @param {string} props.title 输入框标题
 * @param {string} props.prompt 输入框提示
 * @param {string} props.inputValue 输入框的值
 * @param {function} props.setInputValue 设置输入框的值
 * @param {boolean} [props.showModal=false] 是否显示输入框
 * @param {function} [props.onResult] 输入框结果回调
 * @param {ValidatorFunction} [props.validator=()=>null] 输入框验证器
 */
function InputBox(props) {
    let title = props.title;
    let prompt = props.prompt;
    let inputValue = props.inputValue;
    let setInputValue = props.setInputValue;
    let showModal = props.showModal || false;
    let onResult = props.onResult || (() => {});
    let validator = props.validator || (() => null);
    const [validated, setValidated] = useState(false);
    /** @type {React.MutableRefObject<HTMLInputElement>} */
    const inputRef = useRef();
    const [invalidMessage, setInvalidMessage] = useState('');

    const handleResult = (result) => {
        onResult(result);
    };

    const handleClose = () => {
        handleResult(null);
    };

    const handleConfirm = () => {
        let ret = validator(inputValue);
        if (ret === null) {
            handleResult(inputValue);
        } else {
            setValidated(true);
            inputRef.current.setCustomValidity(ret);
            setInvalidMessage(ret);
        }
    };

    return (
        <div>
            <Modal show={showModal}>
                <Modal.Header>
                    <Modal.Title>{title}</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <Form noValidate validated={validated}>
                        <Form.Group>
                            <Form.Label>{prompt}</Form.Label>
                            <Form.Control
                                type="text"
                                value={inputValue}
                                ref={inputRef}
                                onChange={(e) => {
                                    setInputValue(e.target.value);
                                    setValidated(false);
                                }}
                            />
                            <Form.Control.Feedback type="invalid">{ invalidMessage }</Form.Control.Feedback>
                        </Form.Group>
                    </Form>
                </Modal.Body>
                <Modal.Footer>
                    <Button variant="primary" onClick={handleConfirm}>确定</Button>
                    <Button variant="secondary" onClick={handleClose}>取消</Button>
                </Modal.Footer>
            </Modal>
        </div>
    );
}

function ValidatorNotEmpty(value) {
    return value !== '' ? null : '输入不能为空';
}

export default InputBox;
export { ValidatorNotEmpty };
